<template>
  <el-dialog v-model="dialogVisible" destroy-on-close :title="title" width="500px" @close="handleClose">
    <el-form ref="formRef" label-width="100px" :model="formData" :rules="rules">
      <el-form-item v-if="showParentSelect" label="上级审批" prop="parentId">
        <el-select v-model="formData.parentId" placeholder="请选择上级审批">
          <el-option v-for="item in parentOptions" :key="item.pId" :label="item.name" :value="item.pId" />
        </el-select>
      </el-form-item>
      <el-form-item label="审批名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入审批名称" />
      </el-form-item>

      <el-form-item label="审批职务" prop="postsIds">
        <duty-select v-model="formData.postsIds" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注信息" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { ref, watch } from 'vue'
import type { ApprovalProcess, ApprovalProcessParams } from '/@/api/approval/types'

const props = defineProps<{
  modelValue: boolean
  title: string
  formData: Partial<ApprovalProcessParams>
  showParentSelect?: boolean
  parentOptions?: ApprovalProcess[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', data: ApprovalProcessParams): void
}>()

const dialogVisible = ref(props.modelValue)
const formRef = ref<FormInstance>()

const rules = {
  name: [{ required: true, message: '请输入审批名称', trigger: 'blur' }],
  postsIds: [{ required: true, message: '请选择审批职务', trigger: 'change' }],
}

watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val
  }
)

watch(
  () => dialogVisible.value,
  (val) => {
    emit('update:modelValue', val)
  }
)

const handleClose = () => {
  dialogVisible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid) => {
    if (valid) {
      emit('submit', props.formData as ApprovalProcessParams)
    }
  })
}
</script>
